<template>
  <div class="search-box">
    <!-- 筛选条件 -->
    <section class="category-box">
      <div class="breadcrumb knife_container">
        <router-link :to="{name: 'Index'}" class="bread_a">首页</router-link><i class="el-icon-arrow-right"></i>
        <span class="bread_a">全部结果</span> <i class="el-icon-arrow-right"></i> {{searchInput}} 共 
      <em class="color-red">{{amount}}</em>件商品
    </div>
    <div class="category-item knife_container">
      <div class="category-row">
        <span class="category-tit">商品类目</span>
        <section class="category-cont" :class="[collapseCate ? '':'isActive']">
          <div class="collose-tag collose-pos" v-if="cateHeight > 60" @click="collapseCate = !collapseCate">{{collapseCate ? '收起':'展开'}} <i :class="[collapseCate ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i></div>
          <div class="cont-item" ref="refCategory">
            <a v-for="(item, index) in categoryList" @click="clickCondi(item.id, 1)" :key="index" class="cont-item_a" :class="{'active': item.id === Number(categoryIds)}" :data-id="item.id" >
              {{item.name}}
            </a>
          </div>
        </section>
      </div>
      <!-- 品牌-->
      <div class="category-row">
        <span class="category-tit">商品品牌</span>
        <section class="category-cont" :class="[collapseBrand ? '':'isActive']">
          <div class="collose-tag collose-pos" v-if="brandHeight > 60" @click="collapseBrand = !collapseBrand">{{collapseBrand ? '收起':'展开'}} <i :class="[collapseBrand ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i></div>
          <div class="cont-item brand-item" ref="refBrand">
            <a class="cont-item_a" v-for="(brand, brandIndex) in brandList" :key="brandIndex" :data-id="brand.id" 
            :class="{'active': brand.id === Number(brandIds)}" @click="clickCondi(brand.id, 0)">{{brand.name}}</a>
          </div>
        </section>
      </div>
      <!-- 属性 -->
      <div class="category-row" v-if="otherList.length > 0">
        <span class="category-tit">商品属性</span>
        <section class="category-cont" :class="[collapseOther ? '':'isActive']">
          <div class="collose-tag collose-pos" v-if="otherHeight > 60"  @click="collapseOther = !collapseOther">{{collapseOther ? '收起':'展开'}} <i :class="[collapseOther ? 'el-icon-arrow-up':'el-icon-arrow-down']"></i></div>
          <div class="cont-item brand-item" ref="refProperty">
            <a class="cont-item_a" v-for="other in otherList" :key="other"
            :class="{'active': other === others}" @click="clickCondi(other, 2)">{{other}}</a>
          </div>
        </section>
      </div>
    </div>
  </section>
  <!-- 内容 -->
  <section class="search-content knife_container">
    <product class="product-box" :product = "goodsObj.list" ></product>
    <!-- pagination -->
    <el-row v-if="goodsObj.page && goodsObj.page.totalPages > 1">
      <el-pagination class="page_box" background layout="total, prev, pager, next, ->" :current-page="goodsPro.page"
        :total="goodsObj.page.totalRecords | parseIntType" :page-size="goodsObj.page.pageSize | parseIntType" @current-change="handlePage" ></el-pagination>
    </el-row>
  </section>
  </div>
</template>

<script>
import {eventBus} from '@/tool/events-bus'
import {getProSpecList, getGoodsListByKeyword, getCategoryListByKeyword, getBrandListByKeyword, getOtherListByKeyword} from '@/service/get-data'
import {stock, prefixImg} from '@/tool/index'
import {Dialog, Form, FormItem, Button, Input, Col, Row, Tabs, Cascader, TabPane, Table, TableColumn, Pagination, InputNumber, Alert} from 'element-ui'
import {product} from '@/components/index'
import {mapActions, mapState} from 'vuex'
export default {
  components: {
    elDialog: Dialog,
    elForm: Form,
    elFormItem: FormItem,
    elButton: Button,
    elInput: Input,
    elCol: Col,
    elRow: Row,
    elTabs: Tabs,
    elCascader: Cascader,
    elTabPane: TabPane,
    elTable: Table,
    elTableColumn: TableColumn,
    elPagination: Pagination,
    elInputNumber: InputNumber,
    elAlert: Alert,
    product
  },
  data () {
    return {
      collapseCate: false, // 分类是否展开
      collapseBrand: false, // 品牌是否展开
      collapseOther: false, // 其他属性是否展开
      consultVisible: false,
      consultVisibleInner: false, // 咨询内部的弹窗
      consultObj: {
        id: '', // 货品的id
        name: '', // 规格的名称
        consultNum: '' // 咨询弹窗中 输入咨询的数量
      },
      consultdata: '', // 询货结果 null 询货中
      errorObj: { // 错误信息
        text: '请输入正确的数量,最多输入4位',
        status: false
      },
      increaseVisible: false, // 加入购物车弹窗
      increaseProNum: {
        proId: '', // 货品的id
        count: 1 // 添加货品的数量
      },
      proSpecList: {},
      // 规格列表
      searchPro: {
        name: '', // 获取规格列表的name值
        page: '1', // 获取规格列表的page值
        number: '10' // 获取规格列表的number值
      },
      goodsPro: {
        page: 1, // 商品列表的页码
        number: 20 // 商品列表一页的数量
      },
      keyword: '',
      selectType: '', // 主选0为品牌，1为类目
      goodsObj: {}, // 商品列表
      categoryList: [], // 类目列表
      categoryIds: '',
      brandList: [], // 品牌列表
      brandIds: '',
      amount: '',
      goodsId: '', // 获取规格商品的id
      otherList: [],
      others: '',
      shopcartId: '',
      brandHeight: '', // 品牌的高度
      cateHeight: '', // 类目的高度
      otherHeight: '', // 其他属性的高度
      searchedKey: ''
    }
  },
  computed: {
    ...mapState({
      previouskey: state => state.previouskey,
      username: state => state.user.username
    }),
    stock () {
      return stock
    },
    prefixImg () {
      return prefixImg
    },
    searchInput () {
      let route = this.$route.query
      return route.keyword
    }
  },
  methods: {
    ...mapActions(['fetchCartList']),
    eventSearch () {
      let _this = this
      eventBus.$on('searchInput', function (val) {
        _this.keyword = val
        _this.brandIds = ''
        _this.categoryIds = ''
        _this.others = ''
        _this.getAllData()
      })
    },
    // 查看详情
    goToDetail (id) {
      this.$router.push({name: 'productDetail', params: {commodityID: id}})
    },
    // 刷新时的type 层级,typeid 搜索关键字 keyword
    initType () {
      let routequery = this.$route.query
      this.categoryIds = routequery.cateId
      this.brandIds = routequery.brandId
      this.selectType = routequery.selectType || ''
      this.keyword = routequery.keyword
      this.others = routequery.others
      this.goodsPro.page = routequery.page - 0 || 1
    },
    // 点击品牌或者分类
    clickCondi (id, type) {
      this.selectType = type
      type === 1 ? this.categoryIds = id : (type === 0 ? this.brandIds = id : this.others = id)
      this.goodsPro.page = 1 // 页码设置为1
      // this.getAllData()
      this.$router.push({name: 'SearchPage', query: {cateId: this.categoryIds, brandId: this.brandIds, selectType: this.selectType, page: this.goodsPro.page, keyword: this.keyword, others: this.others}})
    },
    getAllData (category, brand) {
      this.fetchGoodsListByKeyword()
      this.fetchCategoryList()
      this.fetchBrandList()
      this.fetchOtherListByKeyword()
    },
    // 关键字搜索商品
    async fetchGoodsListByKeyword () {
      let isNewKeyword = this.searchInput !== this.previouskey && this.searchedKey !== this.searchInput
      let res = await getGoodsListByKeyword(this.goodsPro.page, this.goodsPro.number, this.searchInput, this.categoryIds, this.brandIds, this.others, isNewKeyword, this.username)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.goodsObj = res.data
        this.changeColor(this.goodsObj.list)
        this.amount = res.data.page.totalRecords
        this.searchedKey = this.searchInput
      }
    },
    // 通过关键字获取类目列表
    async fetchCategoryList () {
      let res = await getCategoryListByKeyword(this.searchInput, this.brandIds, this.selectType, this.others)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.$nextTick(() => {
          this.categoryList = res.data
        })
      }
    },
    // 获取其他属性
    async fetchOtherListByKeyword () {
      let res = await getOtherListByKeyword(this.searchInput, this.categoryIds, this.brandIds, this.selectType)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.otherList = res.data
      }
    },
    // 通过关键字获取品牌列表
    async fetchBrandList () {
      let res = await getBrandListByKeyword(this.searchInput, this.categoryIds, this.selectType, this.others)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        this.brandList = res.data
      }
    },
    // 货品规格列表
    async fetchProSpecList () {
      let loadingSpec = this.$loading({target: '.commodity-desc'})
      let res = await getProSpecList(this.goodsId, this.searchPro.page, this.searchPro.number, this.searchPro.name)
      res = res.data
      if (res.resultCode && res.resultCode === 2000) {
        let len = res.data.list.length
        if (len <= 1) {
          this.sigleObj = res.data.list
        }
        this.proSpecList = res.data
        loadingSpec.close()
      } else {
        loadingSpec.close()
        this.message({
          message: '未获取规格列表'
        })
      }
    },
    // 商品列表分页
    handlePage (page) {
      this.goodsPro.page = page
      this.$router.push({name: 'SearchPage', query: {cateId: this.categoryIds, brandId: this.brandIds, selectType: this.selectType, page: this.goodsPro.page, keyword: this.keyword}})
      this.fetchGoodsListByKeyword()
    },
    // 规格页码选择
    page (currentPage) {
      this.searchPro.page = currentPage
      this.fetchProSpecList()
    },
    showConsult (name, id) {
      this.consultVisible = true
      this.consultObj.name = name
      this.consultObj.id = id
    },
    // 关键字高亮
    changeColor (resultsList) {
      resultsList.map((item, index) => {
        if (this.searchInput && this.searchInput.length > 0) {
          let replaceReg = new RegExp(this.searchInput, 'g')
          let repalceStr = `<span class="color-red">${this.searchInput}</span>`
          resultsList[index].originname = item.name
          resultsList[index].name = item.name.replace(replaceReg, repalceStr)
          resultsList[index].other = item.other.replace(replaceReg, repalceStr)
          resultsList[index].brandName = item.brandName.replace(replaceReg, repalceStr)
        }
      })
      this.goodsObj.list = []
      this.goodsObj.list = resultsList
    }
  },

  mounted () {
    this.initType()
    this.getAllData()
  },
  watch: {
    '$route' (val) {
      this.initType()
      this.getAllData()
    },
    // 高度监测
    otherList () {
      this.$nextTick(() => {
        if (this.$refs.refProperty) {
          let height = this.$refs.refProperty.offsetHeight
          this.otherHeight = height
        }
      })
    },
    brandList () {
      this.$nextTick(() => {
        if (this.$refs.refBrand) {
          let height = this.$refs.refBrand.offsetHeight
          this.brandHeight = height
        }
      })
    },
    categoryList () {
      this.$nextTick(() => {
        if (this.$refs.refCategory) {
          let height = this.$refs.refCategory.offsetHeight
          this.cateHeight = height
        }
      })
    }
  },
  filters: {
    parseIntType (val) {
      return parseInt(val)
    }
  }
}
</script>

<style lang="scss" scoped>
  .active{
    color:#FFCC00;
  }
  .category-box {
      position: relative;
      margin-bottom: 20px;
      .category-row{
        overflow: hidden;
        // display: flex;
        border-bottom: 1px solid #e6e6e6;
        // justify-content: flex-start;
        transition: all 0.3s;
        background: #ececec;
      }
      
      .category-tit {
        // display: table-cell;
        background:#ececec;
        text-align: center;
        color: #858585;
        width:90px;
        line-height: 60px;
        font-size: 14px;
        float: left;
      }
      .category-cont{
        // display: table-cell;
        position: relative;
        // flex: 1;
        background: #fff;
        height: auto;
            margin-left: 90px;
      }
      .cont-item {
        // width: 1110px;
        //height: 60px;
        // line-height: 60px;
        border-bottom: 1px solid #e6e6e6;
        padding: 10px 150px 10px 0;
        &:last-child {
          border-bottom: none;
        }
      }
      .cont-item_a{
        color: #666;
        font-size: 14px;
        display: inline-block;
        padding: 13px 30px 13px 32px;
        &.active{
          color:#FFCC00;
        }
      }
       .isActive{
        height: 60px;
        overflow: hidden;
      }
    }
    .collose-tag{
      font-size: 12px;
      color: #999;
      cursor: pointer;
      width: 60px;
      height: 30px;
      line-height: 30px;
      text-align: center;
    }
    .collose-pos{
      position: absolute;
      right: 10px;
      top: 15px;
    }
    // 搜索列表
    .search-content{
      margin-bottom: 50px;
      .pro-img{
        width: 60px;
        height: 60px;
        margin-right: 30px;
        margin-left: 18px;
      }
      .pro-name{
        font-size: 16px;
        color: #333;
        line-height: 22px;
      }
      .pro-amount{
        font-size: 12px;
        color: #666;
      }
      .brand{
        font-size:14px;
        color: #999;
      }
    }
    .shopcart{
      border-radius:4px;
      background: #ffcc00;
      text-align: center;
      color: #fff;
      font-size: 12px;
      line-height: 20px;
      display: inline-block;
      cursor: pointer;
      padding: 8px 22px;
      &:hover{
        color: #fff;
        background:rgba(255,204,0,.85);
      }
    }
    // 规格列表
    .search-div{
    width: 99%;
    box-sizing: border-box;
    position: relative;
    background: #FFFFFF;
    border: 2px solid #DCDCDC;
    border-radius: 4px;
    padding-left: 11px;
    height: 42px;
    line-height: 42px;
    font-size: 14px;
    margin-bottom: 17px;
    input{
      width: 95%;
    }
    i{
      position: absolute;
      float: right;
      @include fontbase(#666666, 22px, 1);
      right: 14px;
      top: 10px;
    }
  }
  .add-to-shop{
    @include fontbase(#ffffff, 12px, 20px);
    display: inline-block;
    cursor: pointer;
    padding: 5px 15px;
    background: #FFCC00;
    border-radius: 2px;
  }
    a{
    &:hover{
      color:#FFCC00;
    }
  }
</style>
